﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using AutoParsers.CustomExceptions;
using HtmlAgilityPack;

namespace AutoParsers
{
    public class MyAutoGeParser : IAutoParser
    {
        public ParsedCar ParseAuto(string url)
        {
            try
            {
                ParsedCar car = new ParsedCar();

                using (WebClient webClient = new WebClient())
                {
                    //Connect and download
                    webClient.Encoding = Encoding.UTF8;
                    webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1468.0 Safari/537.36");
                    HtmlDocument htmlDocument = new HtmlDocument();
                    htmlDocument.LoadHtml(webClient.DownloadString(url));

                    //Parse car info
                    car.URL = url;
                    car.Price = htmlDocument.DocumentNode.SelectSingleNode("//font[@color='#FF0000']").InnerText.Trim();
                    string condition = htmlDocument.DocumentNode.SelectSingleNode("//td[@align='left' and @colspan='2']").InnerText.Trim();
                    car.Condition = condition.Substring(0, condition.Length - 6);
                    //Get list of car specification table
                    HtmlNodeCollection carSpecs = htmlDocument.DocumentNode.SelectNodes("//td[@class='det_val']");
                    
                    car.Manufacturer = htmlDocument.DocumentNode.SelectSingleNode("//td[@class='det_val_first']").InnerText.Trim();

                    //Parse car specifications
                    int shift = htmlDocument.DocumentNode.InnerText.Contains("VIN კოდი:") ? 1 : 0; //If car VIN code exists then sift the specs indexing
                    for (int i = 0; i < carSpecs.Count; i++)
                    {
                        switch (i)
                        {
                            case 0:
                                car.Model = carSpecs[i].InnerText.Trim();
                                break;
                            case 1:
                                car.Year = carSpecs[i].InnerText.Trim();
                                break;
                            case 2:
                                car.Category = carSpecs[i].InnerText.Trim();
                                break;
                            case 3:
                                car.FuelType = carSpecs[i].InnerText.Trim();
                                break;
                            case 4:
                                car.Engine = carSpecs[i].InnerText.Trim();
                                break;
                            case 5:
                                car.Mileage = carSpecs[i].InnerText.Trim();
                                break;
                            case 6:
                                int cylinders;
                                if (Int32.TryParse(carSpecs[i].InnerText.Trim(), out cylinders))
                                {
                                    car.Cylinders = cylinders;
                                }
                                else
                                {
                                    car.Cylinders = null;
                                }
                                break;
                            case 7:
                                car.Transmission = carSpecs[i].InnerText.Trim();
                                break;
                            case 8:
                                car.Drive = carSpecs[i].InnerText.Trim();
                                break;
                            case 9:
                                car.Doors = carSpecs[i].InnerText.Trim();
                                break;
                            case 10:
                                car.IsSteeringRight = carSpecs[i].InnerText.Trim() == "მარჯვნივ";
                                break;
                            case 11:
                                car.Color = carSpecs[i].InnerText.Trim();
                                break;
                            case 12:
                                int airbags;
                                car.Airbags = Int32.TryParse(carSpecs[i].InnerText.Trim(), out airbags) ? airbags : 0;
                                break;
                            case 13:
                                car.BrakeForceSystem = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 14:
                                car.ElWindow = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 15:
                                car.AirConditioning = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 16:
                                car.ClimateControl = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 17:
                                car.LeatherInterior = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 18:
                                car.AluminiumDisks = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 19:
                                car.GPSNavigation = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 20:
                                car.CentralLocking = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 21:
                                car.SunRoof = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 22:
                                car.Alarm = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 23:
                                car.BoardComputer = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 24:
                                car.Hydraulics = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 25:
                                car.Heated = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 26:
                                car.Parking = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                            case 27:
                                car.Turbo = carSpecs[i + shift].InnerHtml.Contains("plus");
                                break;
                        }
                     }
                    
                    //Parse owner. Separate name and phone (ex. John (+995) 577 11 22 33)
                    string ownerData =
                        htmlDocument.DocumentNode.SelectSingleNode(
                            "//b[@style='font-size: 20px;color: #E25A00;margin-left: 10px;']").InnerText.Trim();
                    int nameIndex = ownerData.IndexOf('(');
                    car.Owner = new Owner()
                    {
                        FullName = ownerData.Substring(0, nameIndex - 1),
                        Mobile = ownerData.Substring(nameIndex, ownerData.Length - nameIndex - 1)
                    };

                    //Parse iamges
                    car.Images = new List<string>();
                    string imageHtml = htmlDocument.DocumentNode.SelectSingleNode("//div[@onclick='nextPic();']").OuterHtml;
                    int startIndex = imageHtml.IndexOf("photos");
                    int endIndex = imageHtml.LastIndexOf(".jpg") - 1;
                    string mainImageLink = "http://www.myauto.ge/" + imageHtml.Substring(startIndex, endIndex - startIndex);
                    //count amount of images
                    int imageCount = htmlDocument.DocumentNode.SelectNodes("//div[@id='photosDiv']/table/tr").Count;
                    for (int i = 1; i < imageCount; i++)
                    {
                        car.Images.Add(String.Format("{0}{1}.jpg", mainImageLink, i));
                    }
                }

                return car;
            }
            catch (Exception)
            {
                throw new UnknownUrlException();
            }
        }
    }
}
